package com.jgzx.utils;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.enums.SqlKeyword;
import com.jgzx.constant.YesNoEnum;
import com.jgzx.domain.SeniorCondition;
import com.jgzx.domain.SeniorQueryDTO;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

/**
 * @author libo
 * @date 2021/9/16 14:30
 */
public class SeniorQueryUtil {

    /**
     * 构建高级查询where条件
     * @param seniorQueryDTO 高级查询DTO
     */
    public static SeniorCondition getCondition(SeniorQueryDTO seniorQueryDTO, String alias) {
        List<SeniorQueryDTO.SeniorDetail> seniorDetailList = seniorQueryDTO.getSeniorDetailList();
        SeniorCondition seniorCondition = new SeniorCondition();
        if (CollUtil.isNotEmpty(seniorDetailList)) {
            for (SeniorQueryDTO.SeniorDetail seniorDetail : seniorDetailList) {
                SeniorQueryDTO.FieldOperaEnum opera_symbol = seniorDetail.getOpera_symbol();
                String query_field = seniorDetail.getQuery_field();
                if (StrUtil.isNotEmpty(alias)) {
                    query_field = alias + StrUtil.DOT + query_field;
                }
                List<String> field_values = seniorDetail.getField_values();
                if ("date".equals(seniorDetail.getField_type().getRef())) {
                    query_field = "DATE_FORMAT(" + query_field + ", '%Y-%m-%d')";
                    for (int i = 0; i < field_values.size(); i++) {
                        Date date = formatToBJDate(field_values.get(i));
                        if (date != null) {
                            field_values.set(i, DateUtil.format(date, "yyyy-MM-dd"));
                        }
                    }
                } else {
                    query_field = "IFNULL(" + query_field + ", '')";
                }

                // 除了为空和不为空两个操作符，其他操作符都必须由值
                if (CollUtil.isEmpty(field_values) && !SeniorQueryDTO.FieldOperaEnum.IS_NULL.equals(opera_symbol)
                        && !SeniorQueryDTO.FieldOperaEnum.IS_NOT_NULL.equals(opera_symbol)) {
                    continue;
                }
                // 使用介于条件，必须存在两个值
                if (SeniorQueryDTO.FieldOperaEnum.BETWEEN.equals(opera_symbol) && field_values.size() < 2) {
                    continue;
                }
                switch (opera_symbol) {
                    case EQ:
                        if (field_values.size() == 1) {
                            seniorCondition.eq(query_field, seniorDetail.getField_values().get(0));
                        } else {
                            seniorCondition.in(query_field, seniorDetail.getField_values());
                        }
                        break;
                    case NE:
                        if (field_values.size() == 1) {
                            seniorCondition.ne(query_field, seniorDetail.getField_values().get(0));
                        } else {
                            seniorCondition.notIn(query_field, seniorDetail.getField_values());
                        }
                        break;
                    case LIKE:
                        seniorCondition.like(query_field, seniorDetail.getField_values().get(0));
                        break;
                    case NOT_LIKE:
                        seniorCondition.notLike(query_field, seniorDetail.getField_values().get(0));
                        break;
                    case GT:
                        seniorCondition.gt(query_field, seniorDetail.getField_values().get(0));
                        break;
                    case LT:
                        seniorCondition.lt(query_field, seniorDetail.getField_values().get(0));
                        break;
                    case GE:
                        seniorCondition.ge(query_field, seniorDetail.getField_values().get(0));
                        break;
                    case LE:
                        seniorCondition.le(query_field, seniorDetail.getField_values().get(0));
                        break;
                    case IS_NULL:
                        seniorCondition.isNull(query_field);
                        break;
                    case IS_NOT_NULL:
                        seniorCondition.isNotNull(query_field);
                        break;
                    case BETWEEN:
                        seniorCondition.between(query_field, seniorDetail.getField_values().get(0), seniorDetail.getField_values().get(1));
                        break;
                    default:
                        break;
                }
            }
        }
        seniorCondition.setKey_word(seniorQueryDTO.getKey_word());
        seniorCondition.setOrder(getOrder(seniorQueryDTO, alias));
        return seniorCondition;
    }

    /**
     * 构建排序条件
     * @param seniorQueryDTO 高级查询DTO
     */
    private static String getOrder(SeniorQueryDTO seniorQueryDTO, String alias) {
        String sort_field = seniorQueryDTO.getSort_field();
        if (StrUtil.isNotEmpty(alias) && StrUtil.isNotEmpty(sort_field)) {
            sort_field = alias + StrUtil.DOT + sort_field;
        } else {
            return null;
        }
        return StrUtil.builder().append(sort_field).append(StrUtil.SPACE)
                .append(YesNoEnum.YES.value().equals(seniorQueryDTO.getOrder()) ? SqlKeyword.DESC : SqlKeyword.ASC).toString();
    }

    /**
     * @Author
     * @Description 将UTC时区，转为北京时区
     * @Date 2019/11/14 09:53
     * @Param [dateStr：UTC时间字符串，格式：2018-08-07T01:00:59.000Z]
     * @Return java.util.Date
     **/
    public static Date formatToBJDate(String dateStr) {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
        TimeZone utcZone = TimeZone.getTimeZone("UTC");
        sf.setTimeZone(utcZone);
        try {
            Date date = sf.parse(dateStr);
            return date;
        } catch (Exception e) {
            return null;
        }
    }
}
